package com.ciei.dpagm.util;

import org.apache.commons.lang3.StringUtils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConvertUtil {

    public static String replaceWord(String oldWord,int start,int end,String word) {
        StringBuilder newWord =new StringBuilder(oldWord);
        newWord.replace(start, end,word);
        return newWord.toString();
    }
    private static Pattern linePattern = Pattern.compile("_(\\w)");

    /** 下划线转驼峰 */
    public static String lineToHump(String line) {
        if (StringUtils.isBlank(line))
        {
            return "";
        }
        line = line.toLowerCase();
        Matcher matcher = linePattern.matcher(line);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 驼峰转下划线(简单写法，效率低于{@link #humpToLine2(String)})
     */
    public static String humpToLine(String hump) {
        if (StringUtils.isBlank(hump))
        {
            return "";
        }
        String[] strs = hump.split(" ");
        String head = strs[0].substring(0,1);
        String body = strs[0].substring(1);
        body = body.replaceAll("[A-Z]", "_$0").toLowerCase();
        StringBuilder result = new StringBuilder().append(head).append(body);

        for (int i = 1; i < strs.length; i++)
        {
            result.append(" ").append(strs[i]);
        }
        return result.toString();
    }

    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /** 驼峰转下划线,效率比上面高 */
    public static String humpToLine2(String hump) {
        if (StringUtils.isBlank(hump))
        {
            return "";
        }
        Matcher matcher = humpPattern.matcher(hump);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static String[] lineToHumps(String[] lines)
    {
        if (lines==null)
        {
            return null;
        }

        String[] humps=new String[lines.length];
        for (int i=0;i<lines.length;i++)
        {
            humps[i]=lineToHump(lines[i]);
        }
        return  humps;

    }

    public static String[] humpToLines(String[] humps)
    {
        if (humps==null)
        {
            return null;
        }

        String[] lines=new String[humps.length];
        for (int i=0;i<humps.length;i++)
        {
            lines[i]=humpToLine(humps[i]);
        }
        return  lines;

    }

    /**
     * 驼峰转下划线
     *
     * @param humps key是驼峰型的实体field
     * @return key是下划线型的数据库列
     * @date 2019/12/17
     */
    public static Map<String,Object> humpToLines(Map<String,Object> humps){
        if(humps==null || humps.isEmpty()){
            return humps;
        }
        Map<String,Object> lines = new LinkedHashMap<>(humps.size());
        for(Map.Entry<String,Object> humpEntry: humps.entrySet()){
            lines.put(humpToLine(humpEntry.getKey()),humpEntry.getValue());
        }
        return lines;
    }

//        public static void main(String[] args) {
//            String lineToHump = lineToHump("");
////            String[] lineTohumps=   new String[]{"NameId ASC","DpartmentId DESC"};
////            lineTohumps=humpTolineS(lineTohumps);
////            String[] lineTohumps=lineTohumpS(new String[]{"f_parent_no_leader","f_parent_no_leader"});
//            String[] humpTolines=humpTolineS(new String[]{});
//
////            System.out.println(lineToHump);// fParentNoLeader
////            System.out.println(humpToLine(lineToHump));// f_parent_no_leader
////            System.out.println(humpToLine2(lineToHump));// f_parent_no_leader
//            for (String s:humpTolines)
//            {
//                System.out.println(s);
//            }
////            System.out.println(lineTohumps[0]);
////           System.out.println(humpTolines[0]);
//        }

    /**
     * 将字符串转为对应类型
     * 目前只支持转Integer、Long、Double和Timestamp，按需补充
     * @param value     字符串
     * @param clazz     目标类型
     * @return          转换后的对象
     */
    public static Object convertTypeValue(String value, Class<?> clazz) throws ParseException {
        if (clazz == Integer.class) {
            return StringUtils.isEmpty(value) ? null : Integer.parseInt(value);
        } else if (clazz == Long.class) {
            return StringUtils.isEmpty(value) ? null : Long.parseLong(value);
        } else if (clazz == Double.class) {
            return StringUtils.isEmpty(value) ? null : Double.parseDouble(value);
        } else if (clazz == Timestamp.class) {
            return StringUtils.isEmpty(value) ? null : Timestamp.valueOf(value);
        } else if (clazz == Date.class) {
            return StringUtils.isEmpty(value) ? null : DateUtil.stringToLongDate(value);
        }else if (clazz == Boolean.class) {
            return StringUtils.isEmpty(value) ? null :  Boolean.parseBoolean(value);
        }
        // 按需补充其他类型
        return value;
    }

    /**
     * int转继电器开关状态
     * @param value         数据，从低位到高位每一位代表一个继电器的开关状态
     * @param relayCount    继电器数量，不超过31
     * @return              继电器开关状态
     */
    public static List<Boolean> intToRelayStates(int value, int relayCount) {
        List<Boolean> relayStates = new ArrayList<>();
        if (relayCount == 0) {
            return relayStates;
        }
        int isOn = 1;
        for (int i = 0; i < relayCount; i++) {
            relayStates.add((value & (isOn)) > 0);
            isOn = isOn << 1;
        }

        return relayStates;
    }

}
